import pyautogui
from desktopmagic.screengrab_win32 import (getDisplayRects, getRectAsImage)
import time
import cv2
import numpy as np

# 获取副屏的位置
screens = getDisplayRects()  # 获取所有屏幕


def find_image_on_screen(template_path, threshold=0.96):
    # 读取模板图片
    template = cv2.imread(template_path)
    template_height, template_width = template.shape[:2]
    # 截取整个屏幕
    rect = getRectAsImage(screens[1])
    # 保存截图
    rect.save('test.png')
    screen = cv2.imread("test.png")
    # 模板匹配
    result = cv2.matchTemplate(screen, template, cv2.TM_CCOEFF_NORMED)
    locations = np.where(result >= threshold)
    matches = []
    for pt in zip(*locations[::-1]):
        matches.append({
            'left': pt[0],
            'top': pt[1],
            'width': template_width,
            'height': template_height,
            'confidence': result[pt[1], pt[0]]
        })
    matches.sort(key=lambda x: x['confidence'], reverse=True)
    return matches


# 定义鼠标事件
def mouseClick(img, speed):
    # 查找图片
    matches = find_image_on_screen(img)
    if not matches:
        raise Exception("找不到图片!!!")
    else:
        # 使用最佳匹配
        best_match = matches[0]
        # 计算图片中心位置
        center_x = best_match['left'] + best_match['width'] // 2 + 1920
        center_y = best_match['top'] + best_match['height'] // 2 - 390
        pyautogui.moveTo(center_x, center_y, duration=speed)
        pyautogui.click(clicks=1, duration=speed, button="left")
    time.sleep(0.2)


if __name__ == '__main__':
    yanchi = 0.05
    for i in range(1, 9):
        mouseClick(str(i) + ".png", yanchi)  # 单机次数，
        time.sleep(yanchi)
        pyautogui.write('@')
        time.sleep(yanchi)
        mouseClick(r"sy.png", yanchi)  # 单机次数，
        time.sleep(yanchi)
        pyautogui.hotkey('ctrl', 'v')
        time.sleep(2)
        mouseClick(r"fs.png", yanchi)  # 单机次数，
        time.sleep(2)
